package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;
import com.itheima.service.impl.BrandServiceImplHome;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.调用service查询
        // 接口       变量名      =  new 实现类();  多态, 多条时真正执行的是实现类中的方法, 好处是扩展性强
        BrandService brandService = new BrandServiceImpl();
        List<Brand> brands = brandService.selectAll();

        // 2.将List集合转为JSON
        String json = JSON.toJSONString(brands);

        // 3.响应JSON数据: text/json 告诉浏览器返回的是json格式的数据
        response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(json);
    }
}
